package com.cloud.auth.config;

import com.cloud.auth.properties.AuthProperties;
import com.cloud.common.core.handler.MyAccessDeniedHandler;
import com.cloud.common.core.handler.MyAuthExceptionEntryPoint;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * @Description:Security资源服务器的配置类
 * ResourceServerConfigure继承了ResourceServerConfigurerAdapter，
 * 并重写了configure(HttpSecurity http)方法，
 * 通过requestMatchers().antMatchers("/**")的配置表明该安全配置对所有请求都生效。类上的@EnableResourceServer用于开启资源服务器相关配置。
 * @Auther: zhangxun
 * @Date: 2020/8/7 14:11
 */
@Configuration
@EnableResourceServer
@Data  // 少了这个 anonUrls 注入不进去
@ConfigurationProperties(prefix = "system.config")
// @Order(3)  可以通过@EnableResourceServer 注解查看到Order默认为3
public class ResourceServerConfigure extends ResourceServerConfigurerAdapter {
    @Autowired
    private MyAccessDeniedHandler accessDeniedHandler;
    @Autowired
    private MyAuthExceptionEntryPoint exceptionEntryPoint;

    private String[] anonUrls;
    @Autowired
    private AuthProperties properties;
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .requestMatchers().antMatchers("/**")
                .and()
                .authorizeRequests()
                .antMatchers(anonUrls).permitAll() //免认证资源
                .antMatchers("/**").authenticated()
                .and().httpBasic();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.authenticationEntryPoint(exceptionEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);
    }
}